#include "pt_os.h"

 
unsigned char OSTCBCur;
unsigned char  os_task_index = 0;
PT_OS_TCB_TypeDef pt_os_task[config_max_tasks];
int PtOsTaskCreate(void (*task)(PT_OS_TCB_TypeDef*))
{
	int taskinx = os_task_index++;
	pt_os_task[taskinx].delay = 0;
	pt_os_task[taskinx].one.enable = 1;
	pt_os_task[taskinx].indata = 0;
	pt_os_task[taskinx].outdata = 0;
	pt_os_task[taskinx].task = task;
	pt_os_task[taskinx].callFunState = 0;
	PT_INIT(&pt_os_task[taskinx]);
	return taskinx;
}

void PtOsTimeTick()
{
	for (int i = 0; i < os_task_index; i++) {
		OSTCBCur = i;
		PT_OS_TCB_TypeDef* pt = &pt_os_task[i];
		if (pt->delay == 0) {
			pt->one.rdy = 1;
		}
		else {
			pt->delay = pt->delay - 1;
		}
		if (pt->one.rdy && pt->one.enable) {
			pt->task(pt);
		}
	}
}

void PtOsDelay(unsigned short timeTick) {
	pt_os_task[OSTCBCur].one.rdy = 0;
	pt_os_task[OSTCBCur].delay = timeTick - 1;
}

void PtOsDelayResume(int taskHandle){
    pt_os_task[taskHandle].delay = 0;
}

unsigned long PtGetIndata() {
	return pt_os_task[OSTCBCur].indata;
}

void PtSetInData(int taskHandle, unsigned long indata) {
	pt_os_task[taskHandle].indata = indata;
}

unsigned long PtPopInData() {
	unsigned long v = pt_os_task[OSTCBCur].indata;
	pt_os_task[OSTCBCur].indata = 0;
	return v;
}
int PtPushIndata(int taskHandle, unsigned long indata) {
	if (pt_os_task[taskHandle].indata == 0) {
		pt_os_task[taskHandle].indata = indata;
		return 0;
	}
	return 1;
}

unsigned long PtGetOutdata(int taskHandle) {
	return pt_os_task[taskHandle].outdata;
}

void PtSetOutData(unsigned long outdata) {
	pt_os_task[OSTCBCur].outdata = outdata;
}

unsigned long PtPopOutData(int taskHandle) {
	unsigned long v = pt_os_task[taskHandle].outdata;
	pt_os_task[taskHandle].outdata = 0;
	return v;
}

int PtPushOutdata(unsigned long outdata) {
	if (pt_os_task[OSTCBCur].outdata == 0) {
		pt_os_task[OSTCBCur].outdata = outdata;
		return 0;
	}
	return 1;
}

